package com.wangsh.usersCenter.web.head.interceptor;

import java.net.URLEncoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSONObject;
import com.wangsh.usersCenter.common.controller.BaseController;
import com.wangsh.usersCenter.common.pojo.ApiResponseEnum;
import com.wangsh.usersCenter.common.util.ConstatFinalUtil;
import com.wangsh.usersCenter.outer.service.IClientOuterService;

/**
 * 	登陆验证的拦截器
 * @author wangsh
 */
@Component("authClientInterceptor")
public class AuthClientInterceptor extends BaseController implements HandlerInterceptor
{
	@Resource
	private IClientOuterService clientOuterService;
	
	private String loginUrl = ConstatFinalUtil.CONFIG_JSON.getString("userscenter.back.login.url") ; 
	
	/**
	 * 先执行
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
	{
		ConstatFinalUtil.SYS_LOGGER.info("--preHandle--");
		
		HttpSession session = request.getSession() ; 
		/* 获取用户对象 */
		JSONObject usersJSON = (JSONObject) this.findObjfromSession(request, "users");
		if(usersJSON != null)
		{
			return true ;
		}
		/* 验证Token */
		String[] tokens = request.getParameterValues("token");
		String token = "" ; 
		if(tokens != null && tokens.length > 0)
		{
			token = tokens[tokens.length - 1]; 
		}
		/* 存储数据信息 */
		JSONObject dataReqJSON = new JSONObject();
		try
		{
			if(!"".equalsIgnoreCase(token))
			{
				dataReqJSON.put("token", token);
				/* 验证管理员的token */
				JSONObject responseJSON = this.clientOuterService.verifyAdminsTokenService(dataReqJSON);
				if(ApiResponseEnum.STATUS_SUCCESS.getStatus() == responseJSON.getIntValue("code"))
				{
					JSONObject dataResJSON = (JSONObject) responseJSON.get("data");
					JSONObject usersResJSON = dataResJSON.getJSONObject("users");
					/* 验证成功 */
					session.setAttribute("users", usersResJSON);
					return true ; 
				}
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("请求服务器报错了,url:{};",dataReqJSON,e);
		}
		/* 加上returnUrl */
		String returnUrl = request.getRequestURL() + "";
		String queryStr = request.getQueryString() ;
		if(queryStr == null)
		{
			queryStr = "" ; 
		}
		returnUrl += queryStr ; 
		
		/* 对ReturnUrl进行encode加密 */
		String returnUrlEncode = URLEncoder.encode(returnUrl, "UTF-8");
		
		ConstatFinalUtil.SYS_LOGGER.info("---returnUrl:{}--returnUrlEncode:{}",returnUrl,returnUrlEncode);
		String loginUrl = this.loginUrl + "&returnUrl=" + returnUrlEncode ; 
		response.sendRedirect(loginUrl);
		return false;
	}
}
